import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import iView from "iview";
import { getCookie, setCookie, canTurnTo } from "@/libs/util";

Vue.use(Router);

const router = new Router({
  mode: "history"
});

router.customBeforeEach = function(to, from, next, configRouter) {
  iView.LoadingBar.start();
  const token = getCookie("token");
  const access = getCookie("access");
  const LOGIN_PAGE_NAME = "login";
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    });
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next(); // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: "home" // 跳转到home页
    });
  } else {
    // let user = store.state.user.userInfo;
    // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
    if (access && access !== "undefined") {
      if (canTurnTo(to.name, access, configRouter)) {
        next();
      } else {
        next({ replace: true, name: "error_401" });
      } //有登录权限，无菜单访问权限，重定向到401页面
    } else {
      store.dispatch("handleClientLogOut");
      //权限异常需重新登录
      next({
        name: LOGIN_PAGE_NAME // 跳转到登录页
      });
    }
  }
};

router.customAfterEach = function(to) {
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
};
export default router;
